package org.deng.vertx.web.controller;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: DengLibin
 * @Date: Create in 2022-05-02 18:34:49
 * @Description: 演示
 */
@Slf4j
public class DemoController implements RouterController {

    private Vertx vertx;

    public DemoController(Vertx vertx) {
        this.vertx = vertx;
    }

    @Override
    public void configRouter(Router router) {
        log.info("配置DemoController");
        Route route = router.route("/demo/multiRoute")
                .method(HttpMethod.GET);
        // 添加多个handler
        route
                .handler(this::route1)
                .handler(this::route2)
                .handler(this::route3);

        //执行阻塞代码，交给工作线程执行(不会在事件循环线程中执行)
        router.route("/demo/blockDemo").method(HttpMethod.GET).blockingHandler(this::blockDemo); 

    }

    private void route1(RoutingContext ctx) {
        HttpServerResponse response = ctx.response();
        // enable chunked responses because we will be adding data as
        // we execute over other handlers. This is only required once and
        // only if several handlers do output.
        response.setChunked(true);

        response.write("route1\n");
        //添加数据
        ctx.put("demo_data", "from ctx ");

        // Call the next matching route after a 5 second delay
        ctx.vertx().setTimer(5000, tid -> ctx.next());
    }

    private void route2(RoutingContext ctx) {
        HttpServerResponse response = ctx.response();
        response.write("route2" + ctx.get("demo_data") +"\n");
        
        // Call the next matching route after a 5 second delay
        ctx.vertx().setTimer(5000, tid -> ctx.next());
    }

    private void route3(RoutingContext ctx) {
        HttpServerResponse response = ctx.response();
        response.write("route3");

        // Now end the response
        ctx.response().end();
    }

    /**
     * 使用阻塞
     * @param ctx
     */
    private void blockDemo(RoutingContext ctx) {
        ctx.response().end("this is block service");
    }

}
